﻿using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using PMG.model;
using PMG.data;
using PMG.data.Tool;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using log4net;

public partial class Comsrv : ServerPage
{
    #region 注入对象
    private DaoQUESTIONNAIRE _DaoQUESTIONNAIRE;
    public DaoQUESTIONNAIRE DaoQUESTIONNAIRE
    {
        get { return _DaoQUESTIONNAIRE; }
        set { _DaoQUESTIONNAIRE = value; }
    }

    private DaoQUESTION _DaoQUESTION;
    public DaoQUESTION DaoQUESTION
    {
        get { return _DaoQUESTION; }
        set { _DaoQUESTION = value; }
    }

    private DaoOPTIONS _DaoOPTIONS;
    public DaoOPTIONS DaoOPTIONS
    {
        get { return _DaoOPTIONS; }
        set { _DaoOPTIONS = value; }
    }

    private DaoACCOUNT _DaoACCOUNT;
    public DaoACCOUNT DaoACCOUNT
    {
        get { return _DaoACCOUNT; }
        set { _DaoACCOUNT = value; }
    }

    private DaoANSWER _DaoANSWER;
    public DaoANSWER DaoANSWER
    {
        get { return _DaoANSWER; }
        set { _DaoANSWER = value; }
    }

    private CacheProxy _CacheProxy;
    public CacheProxy CacheProxy
    {
       get { return _CacheProxy;}
       set { _CacheProxy = value; }
    }

    #endregion

    #region page_load
    protected void Page_Load(object sender, EventArgs e)
    {

       Client_Request();

    }
    #endregion

    #region 处理请求分支
    private void Client_Request()
    {
        #region oper
        if (Request["oper"] != null && Request["oper"] != string.Empty)
        {
            
            switch (Request["oper"])
            {
                case "GetQuestionnaire":               //获得问卷
                    int id = int.Parse(Request["qnid"]);
                    GetQuestionnaire(id);
                    break;
                case "GetQN_Cache":               //获得问卷缓存版
                    GetQN_Cache(int.Parse(Request["qnid"]));
                    break;
                case "PutAccount":               //提交Account信息
                    PutAccount();
                    break;
                case "PutAnswer":               //提交Answer信息
                    PutAnswer();
                    break;
                case "PutQuestionnaire":      //新添问卷
                    PutQuestionnaire();
                    break;
                case "PutQuestion":      //提交问题
                    PutQuestion(int.Parse(Request["qnid"]));
                    break;
                case "DelQuestion" :
                    DelQuestion(int.Parse(Request["Qid"]));
                    break;
                case "PutQN":  //提交问卷
                    PutQN(int.Parse(Request["qnid"]));
                    break;
                case "GetAnswer":               //提交Answer信息
                    GetAnswer(int.Parse(Request["qnid"]),int.Parse(Request["Accountid"]));
                    break;
            }
        }
        #endregion
    }   
    #endregion

    // ---------------------- sub action ------------ //
    #region 获得问卷非缓存
    /// <summary>
    /// 获得问卷
    /// </summary>
    private void GetQuestionnaire(int id)
    {
        try
        {
            List<QUESTIONNAIRE> qnList = (List<QUESTIONNAIRE>)DaoQUESTIONNAIRE.SearchByWhere("ID = " + id);
            List<QUESTION> quList = null;
            for (int i = 0; i < qnList.Count; i++)
            {
                quList = (List<QUESTION>)DaoQUESTION.SearchByWhereOrder("QUESTIONNAIREID=" + qnList[i].Id, "ORDERIDX", true);
                for (int j = 0; j < quList.Count; j++)
                {
                    quList[j].Options = (List<OPTIONS>)DaoOPTIONS.SearchByWhere("QUESTIONID=" + quList[j].Id);
                }
                qnList[i].Questions = quList;   


            }

            if (qnList != null)
            {
                string Res = JavaScriptConvert.SerializeObject(qnList);
                OutputJSon(Res);
            }
        }
        catch (Exception ex)
        {
            PMG.data.Tool.Logger.ErrorLog(ex.Source, ex.Message, "GetQuestionnaire");
        }
    }
    #endregion

    #region 获得问卷缓存
    /// <summary>
    /// 获得问卷
    /// </summary>
    private void GetQN_Cache(int id)
    {
            List<QUESTIONNAIRE> qnList = CacheProxy.Cache_GetQuestionnaire(id);
            if (qnList != null)
            {
                string Res = JavaScriptConvert.SerializeObject(qnList);
                OutputJSon(Res);
            }
    }
    #endregion

    #region 提交Account
    /// <summary>
    /// 提交Account
    /// </summary>
    private void PutAccount()
    {
        Encoding myEncoding = Encoding.GetEncoding("utf-8");
        ////对答案进行处理
        Stream stream = Request.InputStream;
        byte[] content = new byte[stream.Length];
        stream.Read(content, 0, content.Length);
        string data = myEncoding.GetString(content).Replace("&_=", string.Empty);

        //data为json
        try
        {
            ACCOUNT acc = (ACCOUNT)JavaScriptConvert.DeserializeObject(data, typeof(ACCOUNT));
            if (DaoACCOUNT.Save(acc))
            {
                OutputJSon(acc.Id.ToString());
            }
        }
        catch (Exception ex)
        {
            PMG.data.Tool.Logger.ErrorLog(ex.Source, ex.Message, "PutAccount");
        }
    }
    #endregion


    #region 提交Answer
    /// <summary>
    /// 提交Account
    /// </summary>
    private void PutAnswer()
    {
        Encoding myEncoding = Encoding.GetEncoding("utf-8");
        ////对答案进行处理
        Stream stream = Request.InputStream;
        byte[] content = new byte[stream.Length];
        stream.Read(content, 0, content.Length);
        string data = myEncoding.GetString(content).Replace("&_=", string.Empty);

        //data为json
        try
        {
            bool isAll = true;
            List<ANSWER> answers = (List<ANSWER>)JavaScriptConvert.DeserializeObject(data, typeof(List<ANSWER>));
            //OutputIlist(data);
            for (int i = 0; i < answers.Count; i++)
            {
                if(!DaoANSWER.Save(answers[i]))
                {
                    isAll = false;
                }
            }
            if (isAll)
            {
                Response.Write("true");
            }
        }
        catch (Exception ex)
        {
            PMG.data.Tool.Logger.ErrorLog(ex.Source, ex.Message, "PutAnswer");
        }
    }
    #endregion


    #region 新添问卷
    /// <summary>
    /// 新添问卷
    /// </summary>
    private void PutQuestionnaire()
    {
        Encoding myEncoding = Encoding.GetEncoding("utf-8");
        ////对答案进行处理
        Stream stream = Request.InputStream;
        byte[] content = new byte[stream.Length];
        stream.Read(content, 0, content.Length);
        string data = myEncoding.GetString(content).Replace("&_=", string.Empty);

        //data为json
        try
        {
            bool isALL = true;
            QUESTIONNAIRE  Qn = (QUESTIONNAIRE)JavaScriptConvert.DeserializeObject(data, typeof(QUESTIONNAIRE));
            Qn.STATE = 0;
            Qn.LSTMODDATE = DateTime.Now;
            Qn.CREATEDATE = DateTime.Now;
            if (DaoQUESTIONNAIRE.Save(Qn))
            {
                for (int i = 0; i < Qn.Questions.Count; i++)
                {
                    Qn.Questions[i].QUESTIONNAIREID = Qn.Id;
                    Qn.Questions[i].LSTMODDATE = DateTime.Now;
                    Qn.Questions[i].CREATEDATE = DateTime.Now;
                    Qn.Questions[i].ORDERIDX = i;
                    if (DaoQUESTION.Save(Qn.Questions[i]))
                    {
                        for(int j=0;j<Qn.Questions[i].Options.Count;j++)
                        {
                            Qn.Questions[i].Options[j].QUESTIONID =Qn.Questions[i].Id;
                            Qn.Questions[i].Options[j].QUESTIONNAIREID = Qn.Id;
                            Qn.Questions[i].Options[j].CREATEDATE = DateTime.Now;
                            Qn.Questions[i].Options[j].LSTMODDATE = DateTime.Now;
                            Qn.Questions[i].Options[j].ORDERX = j;
                            if (!DaoOPTIONS.Save(Qn.Questions[i].Options[j]))
                            {
                                isALL = false;
                            }
                        }
                       
                    }
                    else
                    {
                        isALL = false;
                    }
                }
            }
            else
            {
                isALL = false;
            }

            if (isALL)
            {
                Response.Write("true");
            }
                   
        }
        catch (Exception ex)
        {
            PMG.data.Tool.Logger.ErrorLog(ex.Source, ex.Message, "PutQuestionnaire");
        }
    }
    #endregion


    #region 提交问题
    /// <summary>
    /// 提交问题
    /// </summary>
    private void PutQuestion(int qnid)
    {
        Encoding ec = Encoding.GetEncoding("GB2312");
        ////对答案进行处理
        Stream stream = Request.InputStream;
        byte[] content = new byte[stream.Length];
        stream.Read(content, 0, content.Length);
        string data = ec.GetString(content).Replace("&_=", string.Empty);
        data = System.Web.HttpUtility.UrlDecode(data, ec);

        //data为json
        try
        {
            bool isALL = true;
            QUESTION Q = (QUESTION)JavaScriptConvert.DeserializeObject(data, typeof(QUESTION));
            //新添问题
            if (Q.Id == 0)
            {
                Q.QUESTIONNAIREID = qnid;
                Q.LSTMODDATE = DateTime.Now;
                Q.CREATEDATE = DateTime.Now;
                if (DaoQUESTION.Save(Q))
                {
                    if (Q.TYPE == "singleblank")
                    {
                        OPTIONS o = new OPTIONS();
                        o.QUESTIONID = Q.Id;
                        o.QUESTIONNAIREID = qnid;
                        o.LSTMODDATE = DateTime.Now;
                        o.CREATEDATE = DateTime.Now;
                        o.LABEL = "text";
                        o.VAL = "text";
                        if (!DaoOPTIONS.Save(o))
                        {
                            isALL = false;
                        }

                    }
                    else
                    {
                        for (int i = 0; i < Q.Options.Count; i++)
                        {
                            Q.Options[i].QUESTIONID = Q.Id;
                            Q.Options[i].QUESTIONNAIREID = qnid;
                            Q.Options[i].CREATEDATE = DateTime.Now;
                            Q.Options[i].LSTMODDATE = DateTime.Now;
                            Q.Options[i].ORDERX = i;
                            if (!DaoOPTIONS.Save(Q.Options[i]))
                            {
                                isALL = false;
                            }
                        }
                    }
                }
                else
                {
                    isALL = false;
                }
            }
            else
            {
                Q.QUESTIONNAIREID = qnid;
                Q.LSTMODDATE = DateTime.Now;
                if (DaoQUESTION.Update(Q))
                {

                    SqlHelper.Updata("Delete STB_Options where Questionid=" + Q.Id);
                    if (Q.TYPE == "singleblank")
                    {
                        OPTIONS o = new OPTIONS();
                        o.QUESTIONID = Q.Id;
                        o.QUESTIONNAIREID = qnid;
                        o.LSTMODDATE = DateTime.Now;
                        o.CREATEDATE = DateTime.Now;
                        o.LABEL = "text";
                        o.VAL = "text";
                        if (!DaoOPTIONS.Save(o))
                        {
                            isALL = false;
                        }

                    }
                    else
                    {
                        for (int i = 0; i < Q.Options.Count; i++)
                        {
                            Q.Options[i].QUESTIONID = Q.Id;
                            Q.Options[i].QUESTIONNAIREID = qnid;
                            Q.Options[i].LSTMODDATE = DateTime.Now;
                            Q.Options[i].ORDERX = i;

                            if (!DaoOPTIONS.Save(Q.Options[i]))
                            {
                                isALL = false;
                            }

                        }
                    }
                }
                else
                {
                    isALL = false;
                }
            }

            if (isALL)
            {
                Response.Write("true");
            }

            
        }
        catch (Exception ex)
        {
            PMG.data.Tool.Logger.ErrorLog(ex.Source, ex.Message, "PutQuestion");
        }
    }
    #endregion


    #region 删除问题
    /// <summary>
    /// 删除问题
    /// </summary>
    private void DelQuestion(int Qid)
    {

        try
        {
            QUESTION q = new QUESTION();
            q.Id = Qid;
            if (DaoQUESTION.Delete(q))
            {
                if (SqlHelper.Updata("Delete OPTIONS Where QuestionID=" + Qid) > 0)
                    OutputJSon("true");
            }
        }
        catch (Exception ex)
        {
            PMG.data.Tool.Logger.ErrorLog(ex.Source, ex.Message, "DelQuestion");
        }
    }
    #endregion




    #region 获得答题
    /// <summary>
    /// 获得答题
    /// </summary>
    private void GetAnswer(int qnid, int Accountid)
    {
        try
        {
            List<ANSWER> alist = (List<ANSWER>)DaoANSWER.SearchByWhere("Accountid = " + Accountid + "  and QUESTIONNAIREID = " + qnid);


            if (alist != null)
            {
                string Res = JavaScriptConvert.SerializeObject(alist);
                OutputJSon(Res);
            }
        }
        catch (Exception ex)
        {
            PMG.data.Tool.Logger.ErrorLog(ex.Source, ex.Message, "GetAnswer");
        }
    }
    #endregion


    #region 提交问卷
    /// <summary>
    /// 提交问卷
    /// </summary>
    private void PutQN(int qnid)
    {
        Encoding ec = Encoding.GetEncoding("GB2312");
        ////对答案进行处理
        Stream stream = Request.InputStream;
        byte[] content = new byte[stream.Length];
        stream.Read(content, 0, content.Length);
        string data = ec.GetString(content).Replace("&_=", string.Empty);
        data = System.Web.HttpUtility.UrlDecode(data, ec);

        //data为json
        try
        {
            QUESTIONNAIRE qn = (QUESTIONNAIRE)JavaScriptConvert.DeserializeObject(data, typeof(QUESTIONNAIRE));
            if (qnid > 0)
            {
                qn.LSTMODDATE = DateTime.Now;
                if (DaoQUESTIONNAIRE.Update(qn))
                    OutputJSon(qn.Id.ToString());
            }
            else
            {
                qn.CREATEDATE = DateTime.Now;
                qn.LSTMODDATE = DateTime.Now;
                if (DaoQUESTIONNAIRE.Save(qn))
                    OutputJSon(qn.Id.ToString());
            }
        }
        catch (Exception ex)
        {
            PMG.data.Tool.Logger.ErrorLog(ex.Source, ex.Message, "PutRESPOND");
        }
    }
    #endregion


}
